#include "mainframe.h"
#include "ui_mainframe.h"
#include <QMessageBox>

MainFrame::MainFrame(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainFrame)
{
    ui->setupUi(this);
    bInitSuccess = false;
    qRegisterMetaType<cv::Mat>("cv::Mat");

    initCaptureLib();
}

MainFrame::~MainFrame()
{
    delete ui;
    //English:
    //Chinese:( Encode UTF-8)如果前面申请了很多资源，那么这个执行过后资源就要释放，
    //         此处就是放置释放资源的代码：如申请的内存块释放，类的析构函数执行，如果
    //         使用了cv::VideoCapture cap，那么就要执行 cap.release();函数
    if (bInitSuccess)
        closeCaptureLib();
}

bool MainFrame::initCaptureLib()
{
    // English:press initialize code here,return code can be choosed in need
    // Chinese:(UTF-8 Encoude)此处放置摄像头库初始化代码，返回值根据实际情况修改

    GX_STATUS status = GXInitLib();
    if (status != GX_STATUS_SUCCESS)
    {
        bInitSuccess = false;
        return false;
    }
    //if initalized success
    bInitSuccess = true;
    return true;
}

bool MainFrame::closeCaptureLib()
{
    // English:press initialize code here,return code can be choosed in need
    // Chinese:(UTF-8 Encoude)此处放置摄像头库关闭代码，返回值根据实际情况修改
    GXCloseLib();
    return 1;
}

void MainFrame::on_btStart_clicked()
{
    cap = new Capture;
    int flag =  cap->openCapture(0);
    if (flag == OPEN_SUCCESS)
    {
        connect (cap,SIGNAL(sendMat(cv::Mat)),this,SLOT(showMat(cv::Mat)));
        cap->start();
    }
    else
        QMessageBox::warning(this,"Warning..","Cannot open the capture...",QMessageBox::Ok);

}

void MainFrame::showMat(cv::Mat m)
{
    ui->label->setPixmap(QPixmap::fromImage(MatToImage(m)));
}

void MainFrame::on_btSop_clicked()
{
    cap->stopCapture();
    //terminate the thread,in fact it kill the function:void run()
    cap->terminate();
    //free the memory that belongs to cap
    cap->~Capture();
}
